﻿using System;

namespace Byleist.Caching
{
    public class ValueCache<T>
    {
        private T value;

        private readonly ICacheValueRetrievingPolicy<T> cacheValueRetrievingPolicy;
        private readonly ICacheInvalidationPolicy cacheInvalidationPolicy;

        public ValueCache(ICacheValueRetrievingPolicy<T> cacheValueRetrievingPolicy, ICacheInvalidationPolicy cacheInvalidationPolicy)
        {
            if (cacheValueRetrievingPolicy == null) throw new ArgumentNullException("cacheValueRetrievingPolicy");
            if (cacheInvalidationPolicy == null) throw new ArgumentNullException("cacheInvalidationPolicy");
            this.cacheValueRetrievingPolicy = cacheValueRetrievingPolicy;
            this.cacheInvalidationPolicy = cacheInvalidationPolicy;
        }

        public T GetValue()
        {
            this.cacheInvalidationPolicy.CacheRequested();
            if (this.cacheInvalidationPolicy.IsCacheValid())
            {
                return this.value;
            }
            this.value = this.cacheValueRetrievingPolicy.GetValue();
            this.cacheInvalidationPolicy.CacheRenewed();
            return this.value;
        }
    }
}